package com.beiyou.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.beiyou.dto.GoodsDto;
import com.beiyou.dto.GoodsDtoQuery;
import com.beiyou.dto.UserInfo;
import com.beiyou.local.UserInfoLocal;
import com.beiyou.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.relational.core.sql.In;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import java.util.List;
import java.util.Map;

/**
 * @author wzby
 * @Date: 2022/10/21 10:13
 */
@RestController
@RequestMapping("/api/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @PostMapping
    public Integer insert(@RequestBody GoodsDto goodsDto){
        UserInfo userInfo = UserInfoLocal.get();
        goodsDto.setLastUpdateBy(userInfo.getNickName());
        return goodsService.insert(goodsDto);
    }

    @GetMapping
    //查询所有
    public List<GoodsDto> selectXml(GoodsDtoQuery goodsDtoQuery){
       return goodsService.selectXml(goodsDtoQuery);
    }

    @PatchMapping
    public Integer statusUpdate(@RequestBody Map<String,Integer> map){
        Integer id = map.get("id");
        Integer status = map.get("status");
        return goodsService.statusUpdate(id,status);
    }

    @PutMapping
    public Integer update(@RequestBody GoodsDto goodsDto){
        UserInfo userInfo = UserInfoLocal.get();
        goodsDto.setLastUpdateBy(userInfo.getNickName());
        return goodsService.update(goodsDto);
    }

    @GetMapping("/{id}")
    public GoodsDto selectOne(@PathVariable Integer id){
        GoodsDtoQuery goodsDtoQuery = new GoodsDtoQuery();
        goodsDtoQuery.setId(id);
        return goodsService.select(goodsDtoQuery).get(0);
    }

    @GetMapping("tree")
    public  List<Tree<Integer>> select(){
        List<GoodsDto> goodsDtos = goodsService.select(new GoodsDtoQuery());
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名 都要默认值的
        treeNodeConfig.setWeightKey("seq");
        treeNodeConfig.setIdKey("id");
        // 最大递归深度
        treeNodeConfig.setDeep(2);
        //转换器
        List<Tree<Integer>> treeNodes = TreeUtil.build(goodsDtos, 0, treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId());
                    tree.setParentId(treeNode.getParentId());
                    tree.setWeight(treeNode.getSeq());
                    tree.setName(treeNode.getName());
                    // 扩展属性 ...
                    tree.putExtra("value", treeNode.getId());
                    tree.putExtra("label", treeNode.getName());
                });
        return treeNodes;
    }
}
